import os,sys                       #导入模块

MARK0 = "【非密】"
MARK1 = "【普通商密】"
MARK2 = "【内部】"
MARK3 = "【秘密】"

gDealCount  = 0
gNonlicetFilesCount = 0
def addCount():
    global gDealCount
    gDealCount = gDealCount+1

def getCount():
    global gDealCount
    return gDealCount

def addNonlicetCount():
    global gNonlicetFilesCount
    gNonlicetFilesCount = gNonlicetFilesCount+1

def getNonlicetCount():
    global gNonlicetFilesCount
    return gNonlicetFilesCount

def reNamePath(path, dirMark):
    index = path.rindex("\\")
    fatherpath = path[:index+1]
    dirName = path[index+1:]

    if(dirName.find(MARK0) != -1):
        new_name = dirName.replace(MARK0, dirMark)
    elif(dirName.find(MARK1) != -1):
        new_name = dirName.replace(MARK1, dirMark)
    else:
        new_name = dirMark+dirName

    if (new_name != dirName):
        # 需要修改文件或目录的名字
        addCount()
    try:
        os.rename(os.path.join(fatherpath, dirName), os.path.join(fatherpath, new_name))
    except Exception as e:
        print('warn:', e)

def reName(path):
    dirMark = "【非密】"               #0:非密 1：普通商密
    mark = '【非密】'                   # 默认添加的前缀内容
    old_names = os.listdir( path )     #取路径下的文件名，生成列表
    for old_name in old_names:         #遍历列表下的文件名
        if old_name!= sys.argv[0]:     #代码本身文件路径，防止脚本文件放在path路径下时，被一起重命名
            if(MARK0 in old_name):
                continue
            if(MARK1 in old_name):
                dirMark = MARK1
                continue
            if(MARK2 in old_name or MARK3 in old_name):
                print(path+"\\"+old_name, " 找到一个非法文件 !!!!  ")
                addNonlicetCount()
                continue

            # 未打标识文件，默认打成“【内部】”
            # new_name=old_name.replace('test-','test2-')   #将原来名字里的‘test’替换为‘test2’
            # os.rename(os.path.join(path,old_name),os.path.join(path,new_name))  #子文件夹重命名

            # 需要修改文件或目录的名字
            addCount()
            try:
                os.rename(os.path.join(path,old_name),os.path.join(path,mark+old_name))  #子文件夹重命名
            except Exception as e:
                print('warn:', e)
                os.rename(os.path.join(path, old_name), os.path.join(path, mark + "(1)" + old_name))
                # print (old_name,"has been renamed successfully! New name is: ",mark+old_name)
    #根据子目录及文件标识重新为当前目录打标识
    reNamePath(path, dirMark)

#将当前目录层级下的所有目录加入链表
def appendDir(dirList, path):
    for foldName, subfolders, filenames in os.walk(path):                                     #用os.walk方法取得path路径下的文件夹路径，子文件夹名，所有文件名
        for subfolder in subfolders:                                                          #遍历列表下的子文件夹名
            dirList.append(path+"\\"+subfolder)

def buildTree(dirList, path):
    # print(path, " start buildTree")
    for foldName, subfolders, filenames in os.walk(path):                                     #用os.walk方法取得path路径下的文件夹路径，子文件夹名，所有文件名
        for subfolder in subfolders:                                                          #遍历列表下的子文件夹名
            dirList.append(path+"\\"+subfolder)  # 加入自己
            # print("start append: "+path+"\\"+subfolder)
            buildTree(dirList, path+"\\"+subfolder)
            # os.rename(os.path.join(foldName,subfolder),os.path.join(path,mark+subfolder))     #子文件夹重命名
            # print (subfolder,"has been renamed successfully! New name is: ",mark+subfolder)   #输出提示
            # reName(path)
        break

if __name__ == '__main__':
        # path = r'E:\myTest'   #运行程序前，记得修改主文件夹路径！
        # print("Please enter your filePath:")
        print("=================================说 明=================================\n"
              "    该程序根据以下策略对指定目录作检查修改：\n"
              "     1、如果指定目录及子目录下的文件没有打标识，默认增加【非密】标识；\n"
              "     2、如果某个目录下有【非密】、【普通商密】等多种等级标识的文件及目录，\n"
              "        将检查该目录标识合规性，如不合规，将采用最高等级进行重新标识；\n"
              "     3、如果指定目录下有【内部】、【秘密】等非法文件将进行提示，并统计数量。\n"
              "=======================================================================\n")

        while(1):
            gDealCount = 0
            gNonlicetFilesCount = 0
            path = input("请输入要处理的目录（如:E:\\工作\\项目文档）：")
            if(len(path) == 0 or path.find("\\") == -1):
                print("请输入合法目录！")
                continue

            gDirList = []
            gDirList.append(path)  # 加入自己
            buildTree(gDirList, path)
            while(1):
                if(len(gDirList) == 0):
                    print(" 处理成功，处理目录及文件数量:", getCount(), "个")
                    if(getNonlicetCount() > 0):
                        print(" 找到非法文件数量:", getNonlicetCount(), "，请立即处理！")
                    else:
                        print(" 恭喜你！未找到非法文件！")
                    break
                dir = gDirList.pop()
                # print(dir, " rename start")  # 输出提示
                reName(dir)
            needExit = False
            while(1):
                cmd = input("继续处理其它目录，是(Y)或否(N):")
                if(cmd == "y" or cmd == "Y" or cmd == "是"):
                    needExit = False
                    break
                elif(cmd == "n" or cmd == "N" or cmd == "否"):
                    needExit = True
                    break
                else:
                    print("命令错误，请重新输入！")
                    continue
            if(needExit):
                break

